import java.io.FileInputStream;
import java.io.IOException;

public class ZeroCountingInBinaryFileExample {

	public static int countZeroesByteByByte(String fileName) throws IOException {
		FileInputStream fileStream = new FileInputStream(fileName);
		try {
			int zeroCount = 0;
			int nextByte = 0;
			while ((nextByte = fileStream.read()) != -1) {
				if (nextByte == 0) {
					zeroCount++;
				}
			}
			return zeroCount;
		} finally {
			fileStream.close();
		}
	}
	
	public static int countZeroesWithBuffer(String fileName) throws IOException {
		FileInputStream fileStream = new FileInputStream(fileName);
		try {
			int zeroCount = 0;
			int bytesRead = 0;
			byte[] buf = new byte[64 * 1024];
			while((bytesRead = fileStream.read(buf)) != -1){
				for (int i=0; i<bytesRead; i++) {
					if (buf[i] == 0){
						zeroCount++;
					}
				}
			}
			return zeroCount;
		} finally {
			fileStream.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		long start = System.currentTimeMillis();
		int zeroes = countZeroesByteByByte("pic.jpg");
		long end = System.currentTimeMillis();
		System.out.println("The number of zeroes is: " + zeroes + " operation done in " +  (end - start) + " milis");
		start = System.currentTimeMillis();
		zeroes = countZeroesWithBuffer("pic.jpg");
		end = System.currentTimeMillis();
		System.out.println("The number of zeroes is: " + zeroes + " operation done in " +  (end - start) + " milis");
	}

}
